<!--  jiera-->
<template>
  <div class='bg-white task-handle-container'>
    <div class='handle_type'>{{ handleType }}</div>
    <div class='form-conatiner'>
      <ElForm :model='form' label-width='auto' ref='taskFormRef' :rules='rules'>
        <ElFormItem label='标题' style='width: 100%' prop='title'>
          <ElInput
            v-model='form.title'
            placeholder='请输入帖子标题，最多80字'
            maxlength='80'
          />
        </ElFormItem>
        <ElFormItem label='内容' style='width: 100%' prop='content'>
          <Markdown v-model='form.content' />
        </ElFormItem>
        <ElFormItem label='任务类型' v-if="newTaskType === '0' || newTaskType === undefined">
          <ElRadioGroup v-model='form.type'>
            <ElRadio v-for='item in taskType' :key='item.value' :value='item.value' @change='handleRadioChange'>{{
                item.label
              }}
            </ElRadio>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem label='赏金金额' v-if='form.type === 1' prop='bounty'>
          <ElInputNumber
            v-model.number='form.bounty'
            :precision='2'
            size='large'
            style='width: 20%'
            controls-position='right'
            :min='0'
          />
        </ElFormItem>
        <ElFormItem label='赏金数量' v-if='form.type === 1' prop='bountyNum'>
          <ElInputNumber
            v-model.number='form.bountyNum'
            size='large'
            style='width: 20%'
            controls-position='right'
            :min='0'
          />
        </ElFormItem>
        <ElFormItem label='求助金额' v-if='form.type === 2' prop='helpBounty'>
          <ElInputNumber
            v-model.number='form.helpBounty'
            :precision='2'
            size='large'
            style='width: 20%'
            controls-position='right'
            :min='0'
          />
        </ElFormItem>
        <ElFormItem label='求助数量' v-if='form.type === 2' prop='helpBountyNum'>
          <ElInputNumber
            v-model.number='form.helpBountyNum'
            size='large'
            style='width: 20%'
            controls-position='right'
            :min='0'
          />
        </ElFormItem>
        <ElFormItem label='征召金额' v-if='form.type === 10' prop='bounty'>
          <ElInputNumber
            v-model.number='form.bounty'
            :precision='2'
            size='large'
            style='width: 20%'
            controls-position='right'
            :min='0'
          />
        </ElFormItem>
        <ElFormItem label='征召数量' v-if='form.type === 10' prop='bountyNum'>
          <ElInputNumber
            v-model.number='form.bountyNum'
            size='large'
            style='width: 20%'
            controls-position='right'
            :min='0'
          />
        </ElFormItem>
        <ElFormItem label='目标' v-if='form.type === 10'>
          <ElRadioGroup v-model='form.target'>
            <ElRadio v-for='item in targetType' :key='item.value' :value='item.value'>{{
                item.label
              }}
            </ElRadio>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem label='截止时间' v-if='form.type !== 0'>
          <ElDatePicker
            v-model='form.endTime'
            type='datetime'
            :disabled-date='disabledDate'
            style='width: 71%'
            size='large'
          />
        </ElFormItem>
        <ElFormItem label='封面图片' prop='images'>
          <ElUpload
            action='#'
            list-type='picture-card'
            :http-request='handleUpload'
            :file-list='uploadedFiles'
            @change='handleChange'
          >
            <ElIcon>
              <Plus />
            </ElIcon>
            <template #file>
              <div v-for='(file, index) in uploadedFiles' :key='index'>
                <img class='el-upload-list__item-thumbnail' :src='file.url' alt='' />
                <span class='el-upload-list__item-actions'>
                  <span
                    class='el-upload-list__item-preview'
                    @click='handlePictureCardPreview(file)'
                  >
                    <ElIcon><zoom-in /></ElIcon>
                  </span>
                  <span v-if='!disabled' class='el-upload-list__item-delete'>
                    <ElIcon
                    ><a :href='file.url'><Download /></a
                    ></ElIcon>
                  </span>
                  <span
                    v-if='!disabled'
                    class='el-upload-list__item-delete'
                    @click='handleRemove(file)'
                  >
                    <ElIcon><Delete /></ElIcon>
                  </span>
                </span>
              </div>
            </template>
          </ElUpload>
        </ElFormItem>
        <div style='margin-left: 40%'>
          <ElFormItem>
            <ElButton type='primary' @click='handleSubmit' style='display: inline-block;width: 13%'>提交</ElButton>
            <ElButton type='primary' @click='close' style='display: inline-block;width: 13%'>取消</ElButton>
          </ElFormItem>
        </div>
      </ElForm>
      <el-dialog v-model='dialogVisible'>
        <img w-full :src='dialogImageUrl' alt='Preview Image' />
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { reactive, onMounted, ref } from 'vue'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import Markdown from '@/components/Markdown.vue'
import { useRoute, useRouter } from 'vue-router'
import { ElInputNumber, ElMessage } from 'element-plus'

const taskFormRef = ref()

const route = useRoute()
const router = useRouter()
const handleType = computed(() => {
  return route?.query.typeId === '10' || route?.query.taskType === '10' ? '好友征召' : (route.query.id ? '修改任务' : '新增任务')
})

const taskId = computed(() => route.query?.id as string)
const typeId = computed(() => route.query?.typeId as string)
const newTaskType = computed(() => route.query?.taskType as number)

interface Form {
  title: string,
  description: string,
  content: string,
  endTime: number | string,
  type: number,
  bounty: number,
  bountyNum: number,
  helpBounty: number,
  helpBountyNum: number,
  x: number,
  y: number,
  images: string[],
}

const form = reactive<Form>({
  title: '',
  description: '',
  content: '',
  endTime: '',
  type: 0,
  bounty: 0,
  bountyNum: 0,
  helpBounty: 0,
  helpBountyNum: 0,
  target: '',
  x: 0,
  y: 0,
  images: [],
})

const rules = {
  title: [{ required: true, message: '请输入标题' }],
  content: [{ required: true, message: '请输入内容' }],
  bounty: [
    {
      required: true,
      message: '请输入赏金金额',
    },
    {
      type: 'number',
      required: true,
      message: '赏金金额必须大于0',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (value > 0) {
          callback()
        } else {
          callback(new Error('赏金金额必须大于0'))
        }
      },
    },
  ],
  bountyNum: [
    {
      required: true,
      message: '请输入赏金数量',
    },
    {
      type: 'number',
      required: true,
      message: '赏金数量必须大于0',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (value > 0) {
          callback()
        } else {
          callback(new Error('赏金数量必须大于0'))
        }
      },
    },
  ],
  helpBounty: [
    {
      required: true,
      message: '请输入求助金额',
    },
    {
      type: 'number',
      required: true,
      message: '求助金额必须大于0',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (value > 0) {
          callback()
        } else {
          callback(new Error('求助金额必须大于0'))
        }
      },
    },
  ],
  helpBountyNum: [
    {
      required: true,
      message: '请输入求助数量',
    },
    {
      type: 'number',
      required: true,
      message: '求助数量必须大于0',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (value > 0) {
          callback()
        } else {
          callback(new Error('求助数量必须大于0'))
        }
      },
    },
  ],
}

const getTaskInfo = async (id: number | string) => {
  const result = await service.task.findById(id)
  Object.assign(form, result.data)
  uploadedFiles.value = form.images.map((ele) => ({
    url: ele,
  }))
}

onMounted(() => {
  if (taskId.value != undefined) {
    getTaskInfo(taskId.value)
  }
  if (typeId.value != undefined) {
    if (typeId.value === '1') {
      form.type = 1
    } else if (typeId.value === '2') {
      form.type = 2
    } else if (typeId.value === '10') {
      form.type = 10
      form.target = 0
    }
  } else if (route.query.isHome === '1') {
    form.type = 1
  }
})

const handleRadioChange = (value) => {
  if (value === 10) {
    form.target = 0
  }
}

const taskType = [
  {
    label: '普通帖',
    value: 0,
  },
  {
    label: '赏金帖',
    value: 1,
  },
  {
    label: '求助帖',
    value: 2,
  },
  {
    label: '征召帖',
    value: 10,
  },
]

const targetType = [
  {
    label: '线下',
    value: 0,
  },
  {
    label: '线上',
    value: 1,
  },
]

const disabledDate = (date: Date) => {
  const now = Date.now()
  return date.getTime() <= now - 8.64e7
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const uploadedFiles = ref<any>([])

// 上传封面图片
const handleUpload = async (options: any) => {
  const data = {
    file: options.file,
    filename: options.file.name,
    onProgress: options.onProgress,
  }
  const result = await service.common.upload(data)
  form.images ??= []
  form.images.push(result)
  uploadedFiles.value.push({ url: result })
}
const handleRemove = (file: any) => {
  uploadedFiles.value = uploadedFiles.value.filter((ele: { url: string }) => ele.url != file.url)
  form.images = form.images.filter((ele) => ele != file.url)
  taskFormRef.value.validateField('images')
}

const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const handleChange = () => {
  taskFormRef.value.validateField('images')
}
const location = localStorage.getItem('location') ? JSON.parse(localStorage.getItem('location') as string) : {
  longitude: 120.43717074436847,
  latitude: 31.43021261550411,
}

const handleSubmit = () => {
  taskFormRef.value.validate().then(async (success: boolean) => {
    if (success) {
      form.endTime = form.endTime.valueOf()
      form.x = location.longitude
      form.y = location.latitude
      if (form.type === 1) {
        if (form.bounty <= 0 || form.bountyNum <= 0) {
          ElMessage.error('赏金不能为0')
          return
        }
      }

      if (taskId.value != undefined) {
        await service.task.update(form)
        router.push('/main/home')
      } else {
        await service.task.add(form).then((res) => {
          if (form.type === 1 || form.type === 10) {
            alert('支付账号：sfkxue7105@sandbox.com；登录密码：111111；支付密码：111111' +
              '如果客户端登录失败请下载手机版扫码支付')
            const alipayHtml = res.data
            localStorage.setItem('alipayHtml', '')
            localStorage.setItem('alipayHtml', alipayHtml)
            router.push('/main/pay')
          } else {
            router.push('/main/home')
          }
        })
      }
    }
  })
}
const close = () => {
  router.push('/main/home')
}

</script>

<style lang='scss' scoped>
.task-handle-container {
  padding: 20px 0;

  .handle_type {
    padding: 0 20px 10px;
    margin-bottom: 10px;
    border-bottom: 2px solid rgba(0, 0, 0, 10%);
  }

  .form-conatiner {
    padding: 0 20px;

    .submit_btn {
      width: 300px;
      margin: 0 auto;
    }
  }
}

.submit_btn {
  vertical-align: middle;
  margin-left: 5px; /* 根据需要调整间距数值 */
}
</style>
